package com.anyou.mall.goo.goods.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.anyou.common.core.domain.BaseEntity;
import com.anyou.common.exception.ServiceException;
import com.anyou.common.utils.DateUtils;
import com.anyou.mall.goo.goods.domain.GooGoods;
import com.anyou.mall.goo.goods.dto.GoodsOperationDTO;
import com.anyou.mall.goo.goods.mapper.LiGoodsMapper;
import com.anyou.mall.goo.goods.service.ILiGoodsService;
import com.anyou.mall.goo.goods.vo.GoodsSkuVO;
import com.anyou.mall.goo.goods.vo.SpecValueVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anyou.mall.goo.goods.mapper.LiGoodsSkuMapper;
import com.anyou.mall.goo.goods.domain.LiGoodsSku;
import com.anyou.mall.goo.goods.service.ILiGoodsSkuService;
import org.springframework.transaction.annotation.Transactional;

/**
 * goodSkuService业务层处理
 *
 * @author ruoyi
 * @date 2023-09-16
 */
@Service
public class LiGoodsSkuServiceImpl extends ServiceImpl<LiGoodsSkuMapper, LiGoodsSku> implements ILiGoodsSkuService
{
    @Autowired
    private LiGoodsSkuMapper liGoodsSkuMapper;

    /**
     * 商品
     */
    @Autowired
    private ILiGoodsService goodsService;

    /**
     * 查询goodSku
     *
     * @param id goodSku主键
     * @return goodSku
     */
    @Override
    public LiGoodsSku selectLiGoodsSkuById(Long id)
    {
        return liGoodsSkuMapper.selectLiGoodsSkuById(id);
    }

    /**
     * 查询goodSku列表
     *
     * @param liGoodsSku goodSku
     * @return goodSku
     */
    @Override
    public List<LiGoodsSku> selectLiGoodsSkuList(LiGoodsSku liGoodsSku)
    {
        return liGoodsSkuMapper.selectLiGoodsSkuList(liGoodsSku);
    }

    @Override
    public List<GoodsSkuVO> getGoodsListByGoodsId(String goodsId) {
        List<LiGoodsSku> list = this.list(new LambdaQueryWrapper<LiGoodsSku>().eq(LiGoodsSku::getGoodsId, goodsId));
        return this.getGoodsSkuVOList(list);
    }

    @Override
    public List<GoodsSkuVO> getGoodsSkuVOList(List<LiGoodsSku> list) {
        List<GoodsSkuVO> goodsSkuVOS = new ArrayList<>();
        for (LiGoodsSku goodsSku : list) {
            GoodsSkuVO goodsSkuVO = this.getGoodsSkuVO(goodsSku);
            goodsSkuVOS.add(goodsSkuVO);
        }
        return goodsSkuVOS;
    }

    @Override
    public GoodsSkuVO getGoodsSkuVO(LiGoodsSku goodsSku) {
        //初始化商品
        GoodsSkuVO goodsSkuVO = new GoodsSkuVO(goodsSku);
        //获取sku信息
        JSONObject jsonObject = JSONUtil.parseObj(goodsSku.getSpecs());
        //用于接受sku信息
        List<SpecValueVO> specValueVOS = new ArrayList<>();
        //用于接受sku相册
        List<String> goodsGalleryList = new ArrayList<>();
        //循环提交的sku表单
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            SpecValueVO specValueVO = new SpecValueVO();
            if ("images".equals(entry.getKey())) {
                specValueVO.setSpecName(entry.getKey());
                if (entry.getValue().toString().contains("url")) {
                    List<SpecValueVO.SpecImages> specImages = JSONUtil.toList(JSONUtil.parseArray(entry.getValue()),
                            SpecValueVO.SpecImages.class);
                    specValueVO.setSpecImage(specImages);
                    goodsGalleryList =
                            specImages.stream().map(SpecValueVO.SpecImages::getUrl).collect(Collectors.toList());
                }
            } else {
                specValueVO.setSpecName(entry.getKey());
                specValueVO.setSpecValue(entry.getValue().toString());
            }
            specValueVOS.add(specValueVO);
        }
        goodsSkuVO.setGoodsGalleryList(goodsGalleryList);
        goodsSkuVO.setSpecList(specValueVOS);
        return goodsSkuVO;
    }

    /**
     * 新增goodSku
     *
     * @param liGoodsSku goodSku
     * @return 结果
     */
    @Override
    public int insertLiGoodsSku(LiGoodsSku liGoodsSku)
    {
        liGoodsSku.setCreateTime(DateUtils.getNowDate());
        return liGoodsSkuMapper.insertLiGoodsSku(liGoodsSku);
    }

    /**
     * 修改goodSku
     *
     * @param goods
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GooGoods goods, GoodsOperationDTO goodsOperationDTO)
    {
        // 是否存在规格
        if (goodsOperationDTO.getSkuList() == null || goodsOperationDTO.getSkuList().isEmpty()) {
            throw new ServiceException("规格必须要有一个");
        }
        List<LiGoodsSku> skuList;
        //删除旧的sku信息
        if (Boolean.TRUE.equals(goodsOperationDTO.getRegeneratorSkuFlag())) {
            skuList = GoodsSkuBuilder.buildBatch(goods, goodsOperationDTO.getGoodsSkus());

            List<GoodsSkuVO> goodsListByGoodsId = getGoodsListByGoodsId(Long.toString(goods.getGoodsId()));
        } else {
            skuList = new ArrayList<>();
            for (Map<String, Object> map : goodsOperationDTO.getGoodsSkus()) {
                LiGoodsSku sku = GoodsSkuBuilder.build(goods, map);
                skuList.add(sku);
            }
        }
        if (!skuList.isEmpty()) {
            LambdaQueryWrapper<LiGoodsSku> unnecessarySkuIdsQuery = new LambdaQueryWrapper<>();
            unnecessarySkuIdsQuery.eq(LiGoodsSku::getGoodsId, goods.getGoodsId());
            unnecessarySkuIdsQuery.isNotNull( LiGoodsSku::getGoodsId).notIn(LiGoodsSku::getId,
                    skuList.stream().map(LiGoodsSku::getId).filter(getId->getId!=null).collect(Collectors.toList()));
            this.remove(unnecessarySkuIdsQuery);
            this.saveOrUpdateBatch(skuList);
            this.updateStock(skuList);
        }
    }

    @Override
    public void updateSku(GooGoods goods, List<LiGoodsSku> skuList) {
        LambdaQueryWrapper<LiGoodsSku> unnecessarySkuIdsQuery = new LambdaQueryWrapper<>();
        unnecessarySkuIdsQuery.eq(LiGoodsSku::getGoodsId, goods.getGoodsId());
        unnecessarySkuIdsQuery.isNotNull( LiGoodsSku::getGoodsId).notIn(LiGoodsSku::getId,
                skuList.stream().map(LiGoodsSku::getId).filter(getId->getId!=null).collect(Collectors.toList()));
        this.remove(unnecessarySkuIdsQuery);
        this.saveOrUpdateBatch(skuList);
        this.updateStock(skuList);
    }

    /**
     * 批量删除goodSku
     *
     * @param ids 需要删除的goodSku主键
     * @return 结果
     */
    @Override
    public int deleteLiGoodsSkuByIds(Long[] ids)
    {
        return liGoodsSkuMapper.deleteLiGoodsSkuByIds(ids);
    }

    /**
     * 删除goodSku信息
     *
     * @param id goodSku主键
     * @return 结果
     */
    @Override
    public int deleteLiGoodsSkuById(Long id)
    {
        return liGoodsSkuMapper.deleteLiGoodsSkuById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GooGoods goods, GoodsOperationDTO goodsOperationDTO) {
        // 是否存在规格
        if (goodsOperationDTO.getGoodsSkus() == null || goodsOperationDTO.getGoodsSkus().isEmpty()) {
            throw new ServiceException("规格必须要有一个！");
        }
        // 检查是否需要生成索引
        List<LiGoodsSku> goodsSkus = GoodsSkuBuilder.buildBatch(goods, goodsOperationDTO.getGoodsSkus());

        if (!goodsSkus.isEmpty()) {
            this.saveOrUpdateBatch(goodsSkus);
            this.updateStock(goodsSkus);
        }
    }

    /**
     * 修改库存
     *
     * @param goodsSkus 商品SKU
     */
    private void updateStock(List<LiGoodsSku> goodsSkus) {
        //总库存数量
        Integer quantity = 0;
        for (LiGoodsSku sku : goodsSkus) {
            quantity += sku.getQuantity();
        }
        //修改商品库存
        goodsService.updateStock(goodsSkus.get(0).getGoodsId(), quantity);
    }

}
